<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 通用工具栏组件使用 -->
      <page-tools>
        <!-- 自定义左侧内容 -->
        <template #slot-left>
          <span>共19条记录</span>
        </template>

        <!-- 自定义右侧内容 -->
        <template #slot-right>
          <el-button
            type="danger"
            size="small"
            @click="$router.push('/excel')"
          >导入excel</el-button>
          <el-button
            type="success"
            size="small"
            @click="exportExcelFn"
          >导出excel</el-button>
          <el-button
            type="primary"
            size="small"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </page-tools>

      <!-- 表格体 -->
      <el-card style="margin-top: 10px">
        <el-table border :data="employeesList">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto" />
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column
            sortable
            label="工号"
            prop="workNumber"
            :formatter="formatWorkNumberFn"
            :sort-method="sortWorkNumberFn"
          />
          <el-table-column label="聘用形式">
            <template v-slot="scope">
              <span>{{ formatEmployeeFn(scope.row.formOfEmployment) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template v-slot="scope">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${scope.row.id}`)">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <!-- 分页区域 -->
          <el-pagination
            :current-page="query.page"
            :page-sizes="[10, 15, 20, 25]"
            :page-size="query.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>

      <!-- 新增员工 - 弹窗 -->
      <el-dialog
        title="新增员工"
        :visible.sync="showDialog"
        @close="dialogCloseFn"
      >
        <EmpForm
          ref="empForm"
          :tree-data="treeData"
          @close="formCloseFn"
          @add-emp="addEmpFn"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getEmployeeListAPI,
  getDepartmentsListAPI,
  addEmployeeAPI
} from '@/api'
import EmpForm from './components/empForm.vue'
// 树状扁平化
import { transTree } from '@/utils'

export default {
  name: 'Employees',
  components: {
    EmpForm
  },
  data() {
    return {
      query: {
        page: 1, // 页码
        size: 10 // 每页条数
      },
      employeesList: [], // 员工列表
      total: 0, // 数据总条数
      showDialog: false, // 新增员工 - 弹窗是否会出现
      treeData: [] // 部门的数据
    }
  },

  created() {
    this.getEmployeeListFn()
    this.getDepartmentsListFn()
  },

  methods: {
    // 请求 - 部门列表的数据
    async getDepartmentsListFn() {
      const res = await getDepartmentsListAPI()
      // console.log(res)
      if (!res.data.success) return this.$message.error(res.data.message)
      this.treeData = transTree(res.data.data.depts, '')
      // console.log(this.treeData)
    },

    // 请求 - 员工列表数据
    async getEmployeeListFn() {
      const res = await getEmployeeListAPI(this.query)
      // console.log(res)
      if (!res.data.success) return this.$message.error(res.data.message)
      this.$message.success(res.data.message)
      this.employeesList = res.data.data.rows
      this.total = res.data.data.total
    },

    // 聘用形式 - 数字转中文
    formatEmployeeFn(str) {
      // console.log(str)
      if (String(str) === '1' || str === '正式') {
        return '正式'
      } else {
        return '非正式'
      }
    },

    // 工号 - 格式化
    formatWorkNumberFn(row) {
      // console.log(row)
      return row.workNumber * 1
    },

    // 工号 - 自定义排序过程
    sortWorkNumberFn(a, b) {
      // console.log(a, b)
      return a.workNumber - b.workNumber
    },

    // 表单 - 确定和取消按钮 - 弹窗关闭
    formCloseFn() {
      this.showDialog = false
    },

    // 每页显示的条数发生改变时触发
    handleSizeChange(newSize) {},

    // 当前页面发生改变时触发
    handleCurrentChange(newPage) {},

    // 表单 - 确定按钮 -> 添加员工
    async addEmpFn(formData) {
      const res = await addEmployeeAPI(formData)
      console.log(res)
    },

    // 弹窗被关闭->检测到事件
    dialogCloseFn() {
      this.$refs.empForm.$refs.addForm.resetFields()
    },

    // 表格 - 导出 - 点击事件
    exportExcelFn() {
      import('@/vendor/Export2Excel').then((excel) => {
        const obj = {
          id: '编号',
          username: '姓名',
          staffPhoto: '头像地址',
          mobile: '手机号',
          workNumber: '工号',
          formOfEmployment: '聘用形式',
          departmentName: '部门',
          timeOfEntry: '入职日期',
          password: '密码',
          correctionTime: '转正日期'
        }
        const rowArr = this.employeesList // 员工列表数组
        // 因为所有对象的key一致,默认取第一个对象出来
        const rowObj = rowArr[0]
        // 把所有key取出来形成一个新数组
        const keysArr = Object.keys(rowObj)
        const headerArr = keysArr.map((key) => {
          const zhkey = obj[key]
          return zhkey
        })
        const data = rowArr.map((item) => {
          return Object.values(item)
        })
        excel.export_json_to_excel({
          header: headerArr,
          data,
          filename: '1.xlsx',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
